let myTools = require('./libs/mytools');

cc.Class({
    extends: cc.Component,

    properties: {

        sp_battery_1: cc.Sprite,
        sp_battery_2: cc.Sprite,

        sp_bg: cc.Sprite,
        nd_chainLayer: cc.Node,
        nd_allArea: cc.Node,

        // prefabs
        pf_chain: cc.Prefab,
        pf_selnode: cc.Prefab,
        pf_bkp: cc.Prefab,

        nd_selectedFlag: cc.Node,
        nd_anchor: cc.Node, // 表示选择到的物体描点

        nd_movieMode: cc.Node,
    },

    ctor() {
        this._chainDrawMode = G.ChainDrawMode.Line;
    },

    onLoad() {
        // for gui
        G.gameMap = G.gameApp = this;

        this.nd_scope = cc.find('scope', this.sp_battery_1.node);
        this.sp_battery_2.node.active = false;
        this.nd_scope.active = false;

        this.offsetX = this.node.width - 720;
        this.offsetY = this.node.height - 1280;

        this.nd_selectedFlag.zIndex = 100;

        this.curSel = null;
        this.curChain = null;
        this.lstChain = [];

        let chain = this._createChain();
        this.setCurChain(chain);

        this.nd_movieMode.zIndex = 200;
    },

    _createChain() {
        let nd_chain = cc.instantiate(this.pf_chain);
        nd_chain.setParent(this.nd_chainLayer);

        let chain = nd_chain.getComponent('chain');
        this.lstChain.push(chain);
        chain.updateDrawMode(this._chainDrawMode);
        return chain;
    },

    initDecos() {

        if (!this.sp_battery_1.id) {
            cc.log('给deco产生id');
            this.sp_battery_1.id = myTools.genId();
        }
        if (!this.sp_battery_2.id) {
            this.sp_battery_2.id = myTools.genId();
        }

        myTools.mixObj({
            isBattery: function () {
                return true;
            },
        }, this.sp_battery_1);
        myTools.mixObj({
            isBattery: function () {
                return true;
            },
        }, this.sp_battery_2);
        this.sp_battery_1.alias = settings.default_battery_1;
        this.sp_battery_2.alias = settings.default_battery_2;

        let lstDeco = editor.getDecoView().getModel();
        lstDeco.push(this.sp_battery_1);
        lstDeco.push(this.sp_battery_2);
        editor.getDecoView().updateModel(lstDeco);

        // selectedFlag
        this.nd_selectedFlag.active = false;
        this.nd_anchor.active = false;

        // 编辑器节点状态
        editor.changeState(editor.editChainState);
    },

    start() {
        this.nd_allArea.on(cc.Node.EventType.TOUCH_START, this.touchBegin, this, false);
        this.nd_allArea.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this, false);
        this.nd_allArea.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this, false);
        this.nd_allArea.on(cc.Node.EventType.TOUCH_CANCEL, this.touchCancel, this, false);
    },

    getChainbDrawMode() {
        return this._chainDrawMode;
    },

    touchBegin(event) {
        let curState = editor.getCurState();
        curState.touchBegin(event);
    },
    touchMove(event) {
        let curState = editor.getCurState();
        curState.touchMove(event);
    },
    touchEnd(event) {
        let curState = editor.getCurState();
        curState.touchEnd(event);
    },
    touchCancel(event) {
        let curState = editor.getCurState();
        curState.touchCancel(event);
    },

    /// apis for gui
    showSingleBattery() {
        this.sp_battery_1.node.active = true;
        this.sp_battery_2.node.active = false;
    },
    showDoubleBattery() {
        this.sp_battery_1.node.active = true;
        this.sp_battery_2.node.active = true;
    },

    /**
     *
     * @return {cc.Node | *}
     */
    getDefaultBattery() {
        return this.sp_battery_1;
    },

    showBlack(moiveMode) {
        if (moiveMode) {
            this.nd_movieMode.active = true;
        } else {
            this.nd_movieMode.active = false;
        }
    },

    getSelectChain() {
        return this.curChain;
    },


    //----------------------
    pickSel(localPos) {
        for (let i = 0, len = this.lstChain.length; i < len; ++i) {
            let chain = this.lstChain[i];
            let sel = chain.selectSel(localPos);
            if (sel) {
                return sel;
            }
        }
        return null;
    },

    setCurSel(sel) {
        this.curSel = sel;
        this.lstChain.forEach(chain => {
            chain.highlightSel(sel);
        });
        if (sel) {
            this.setCurChain(sel.getChain());
        }
    },

    setCurChain(newChain) {
        if (this.curChain !== newChain) {
            this.curChain = newChain;
            console.log('切换 chain...');
            if (newChain) {
                if (window.editor) {
                    editor.getBkpView().changeChain(newChain);
                }
            } else {
                console.error('应该不会如此....');
            }
        }
    },

    // addChain() {
    //     // // 在右上角创建一个sel node
    //     // if (this.curChain.lstSel.length < 1) {
    //     //     let curChain = this.curChain;
    //     //     curChain.addSel(cc.v2(this.node.width - 50, this.node.height - 50));
    //     //     return null;
    //     // } else {
    //     //     let chain = this._createChain();
    //     //     chain.addSel(cc.v2(this.node.width - 50, this.node.height - 50));
    //     //     return chain;
    //     // }
    //
    //     // 在右上角创建一个sel node
    //     let chain;
    //     if (this.curChain.lstSel.length < 1) {
    //         chain = this.curChain;
    //     } else {
    //         chain = this._createChain();
    //     }
    //     chain.addSel(cc.v2(this.node.width - 50, this.node.height - 50));
    // },

    selectDeco(sp) {
        editor.getInspectView().updateInspectView(sp);
        editor.getDecoView().selectSprite(sp);
    },

    showSelectedFlag() {
        let nd_select = editor.getInspectView().getSelectedSp().node;
        let w = nd_select.width * nd_select.scaleX;
        let h = nd_select.height * nd_select.scaleY;
        let x = nd_select.x;
        let y = nd_select.y;
        let degress = nd_select.angle;

        this.nd_selectedFlag.active = true;
        this.nd_selectedFlag.setAnchorPoint(nd_select.anchorX, nd_select.anchorY);
        this.nd_selectedFlag.setContentSize(w, h);
        this.nd_selectedFlag.setPosition(x, y);
        this.nd_selectedFlag.angle = degress;
        this.nd_anchor.active = true;
        this.nd_anchor.setPosition(0, 0);
    },

    hideSelectedFlag() {
        this.nd_selectedFlag.active = false;
    },

    setBg(domLabelBgPath, bgFullPath) {
        let self = this;

        let oldFrame = self.sp_bg.spriteFrame;
        if (oldFrame) {
            cc.log('先删除旧的...');
            cc.assetManager.releaseAsset(oldFrame);
        }

        // 验证下后缀
        let extname = window.path.extname(bgFullPath).toLowerCase();
        if (extname === '.png' ||
            extname === '.jpg' ||
            extname === '.jpeg') {
            // 先加载新的背景
            // 再删除老的背景
            cc.assetManager.loadRemote(bgFullPath, (err, texture) => {
                if (err) {
                    throw err;
                }
                domLabelBgPath.value = bgFullPath;

                // 应用新的
                self.sp_bg.spriteFrame = new cc.SpriteFrame(texture);
            });
        } else {
            settings.alert('背景只支持 .png 和 .jpg/.jpeg 格式!');
        }
    },

    removeBg() {
        let frame = this.sp_bg.spriteFrame;
        this.sp_bg.spriteFrame = null;
        if (frame) {

            cc.log('释放背景...');
            // cocos 2.4.2 bug????
            cc.assetManager.releaseAsset(frame._texture);
            cc.assetManager.releaseAsset(frame);
        }
    },

    setChainType(newType) {
        if (this._chainDrawMode === newType) {
            return;
        }
        this._chainDrawMode = newType;
        this.lstChain.forEach(chain => {
            chain.updateDrawMode(newType);
        });
    },

    // /**
    //  * 删除当前 chain.
    //  */
    // deleteChain() {
    //
    //     this.setCurSel(null);
    //
    //     // 如果当前只剩下一个chain,则只删除数据
    //     if (this.lstChain.length > 1) {
    //         let idx = this.lstChain.indexOf(this.curChain);
    //         if (idx >= 0) {
    //             this.lstChain.splice(idx, 1);
    //             this.curChain.clean();
    //             this.curChain.node.destroy();
    //         }
    //         this.setCurChain(this.lstChain[0]);
    //     } else {
    //         this.curChain.clean();
    //     }
    // },

    removeChain(chain){
        if(!chain){
            throw new Error('chain is null!');
        }
        if(this.lstChain.length > 1){
            let idx = this.lstChain.indexOf(chain);
            if (idx >= 0) {
                this.lstChain.splice(idx, 1);
                chain.clean();
                chain.node.destroy();
            }
            this.setCurChain(this.lstChain[0]);
        }else{
            chain.clean();
        }
    },


    onAddDecoSprite(decoPath,frame, pos) {
        let nd = new cc.Node();
        let sp = nd.addComponent(cc.Sprite);
        sp.spriteFrame = frame;
        nd.setPosition(pos.x, pos.y);
        nd.setParent(this.node);

        myTools.mixObj({
            isBattery: function () {
                return false;
            },
        }, sp);
        if (!sp.id) {
            sp.id = myTools.genId();
        }

        sp.decoPath = decoPath;

        let lstDeco = editor.getDecoView().getModel();
        lstDeco.push(sp);
        editor.getDecoView().updateModel(lstDeco);

        // 判断当前状态
        if (!editor.isViewState()) {
            this.selectDeco(sp);
        }
        return sp;
    },


    delDecoSp() {
        let selectSp = editor.getInspectView().getSelectedSp();
        if (!selectSp) {
            return;
        }

        let lstDeco = editor.getDecoView().getModel();
        let idx = lstDeco.indexOf(selectSp);
        if (idx >= 0) {
            lstDeco.splice(idx, 1);
            selectSp.node.destroy();
            editor.getInspectView().updateInspectView(null);
            editor.getDecoView().updateModel(lstDeco);
        }
    },


    parseChainDatas(lstChainDatas) {
        if (lstChainDatas.length < 1) {
            return;
        }

        if (lstChainDatas.length > 2) {
            settings.alert('chains 数据不正确!');
            return;
        }

        // 因为默认会有一个chain,所以这里只需要再添加一个即可
        if (lstChainDatas.length === 2) {
            this._createChain();
        }

        lstChainDatas.forEach((chainData, idx) => {
            let chain = this.lstChain[idx];
            chain.parseData(chainData);
        });
    },

    // export model
    getChainModel() {
        let lst = [];
        this.lstChain.forEach(chain => {
            let model = chain.getModel();
            if (model) {
                lst.push(model);
            }
        });
        return lst;
    },


    getChainIdx(chain){
        for(let i = 0; i < this.lstChain.length; ++i){
            if(this.lstChain[i] === chain){
                return i;
            }
        }
        return -1;
    },

    getChainByIdx(idx){
        if(idx > 1 || idx < 0){
            throw new Error(`idx:${idx} error!`);
        }
        return this.lstChain[idx];
    }
});
